package com.lyy.component;

import cn.hutool.core.util.ObjectUtil;
import com.lyy.util.RedisUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * @author Liangyaoyun
 */
@Slf4j
@Component
public class PointsTask {
    @Autowired
    private RedisUtil redisUtil;

    private final String POINTS_KEY_PREFIX="lesson:points:user-";

    /**
     * 用户下单购买成功后，异步为用户添加积分
     *
     * @param userId User主键
     * @param totalFee 订单总金额
     * @return Future类型的提示字符串
     *
     */
    @SneakyThrows
    @Async
    public Future<String>addPoints(Integer userId,double totalFee){
        //校验参数
        if (ObjectUtil.hasNull(userId,totalFee)){
            throw new RuntimeException("必要参数为空");
        }

        //组装key值:使用固定前缀拼接用户的主键字符串作为key值
        String key=POINTS_KEY_PREFIX+userId;
        //添加积分
        redisUtil.incr(key,totalFee);
        //打印成功日志
        log.info("积分添加成功");
        return new AsyncResult<>("积分添加成功");
    }
}
